package com.l.dbtransfer.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.io.FileUtils;

/**
 * Created by 严秋旺
 */
public class ConfigUtils {
    public static final String path = "config.properties";
    static Properties properties = new Properties();

    static {
        File file = new File(path);

        InputStream inputStream = null;
        try {
            if (file.exists()) {
                inputStream = new FileInputStream(file);
            } else {
                System.out.println("外部配置文件[" + path + "]不存在，使用内部配置文件");
                inputStream = ConfigUtils.class.getResourceAsStream("/" + path);
                FileUtils.copyInputStreamToFile(inputStream, file);
                System.out.println("复制配置文件模板到"+file.getAbsolutePath());
                inputStream = new FileInputStream(file);
            }

            properties.load(inputStream);
            inputStream.close();
        } catch (IOException e) {
            System.out.println("配置文件读取错误");
            e.printStackTrace();
        }finally {
            if(inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取配置
     *
     * @param key 配置项key
     * @return 配置项值
     */
    public static String getProperty(String key) {
        return properties.getProperty(key);
    }

}
